package com.vegetable.modules.service.wx;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.modules.entity.wx.WXApproval;
import com.vegetable.modules.mapper.wx.WXApprovalDao;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.WxCpApprovalDetailResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 企业微信审批定时任务
 * 作为异步回调的备份机制，处理可能遗漏的审批回调
 *
 * @author Qoder
 */
@Slf4j
@Component
public class WxApprovalScheduledTask {

    @Autowired
    private WxCpService wxCpService;

    @Autowired
    private WXApprovalService wxApprovalService;

    @Autowired
    private WXApprovalDao wxApprovalDao;

    /**
     * 每5分钟检查一次未处理的审批
     * 处理可能遗漏的审批回调
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkPendingApprovals() {
        try {
            log.info("开始检查未处理的企业微信审批");
            
            // 查询状态为"审批中"的审批记录
            QueryWrapper<WXApproval> wrapper = new QueryWrapper<>();
            wrapper.eq("sp_status", "AUDITING"); // AUDITING表示审批中
            
            List<WXApproval> pendingApprovals = wxApprovalService.list(wrapper);
            
            if (pendingApprovals.isEmpty()) {
                log.info("没有未处理的审批记录");
                return;
            }
            
            log.info("发现 {} 条未处理的审批记录，开始处理", pendingApprovals.size());
            
            // 处理每条未处理的审批
            for (WXApproval approval : pendingApprovals) {
                try {
                    // 如果数据库状态是 ALREADY_PAY 或 PASSED，跳过更新
                    String dbStatus = approval.getSpStatus();
                    if ("ALREADY_PAY".equals(dbStatus) || "PASSED".equals(dbStatus)) {
                        log.info("审批编号: {} 数据库状态为 {}，跳过更新", approval.getSpNo(), dbStatus);
                        continue;
                    }
                    
                    // 获取审批详情
                    WxCpApprovalDetailResult detailResult = wxCpService.getOaService().getApprovalDetail(approval.getSpNo());
                    
                    if (detailResult != null && detailResult.getErrCode() == 0) {
                        // 更新审批状态
                        WxCpApprovalDetailResult.WxCpApprovalDetail approvalInfo = detailResult.getInfo();
                        String currentStatus = approvalInfo.getSpStatus().name();
                        
                        // 如果状态已变更，则更新数据库
                        if (!currentStatus.equals(approval.getSpStatus())) {
                            approval.setSpStatus(currentStatus);
                            approval.setSpComment(com.alibaba.fastjson.JSON.toJSONString(detailResult));
                            approval.setUpdateTime(new java.util.Date());
                            
                            wxApprovalDao.updateById(approval);
                            log.info("更新审批状态，审批编号: {}, 新状态: {}", approval.getSpNo(), currentStatus);
                        }
                    } else {
                        log.warn("获取审批详情失败，审批编号: {}, 错误码: {}", approval.getSpNo(), 
                            detailResult != null ? detailResult.getErrCode() : "null");
                    }
                } catch (WxErrorException e) {
                    log.error("处理审批记录时发生微信异常，审批编号: {}", approval.getSpNo(), e);
                } catch (Exception e) {
                    log.error("处理审批记录时发生异常，审批编号: {}", approval.getSpNo(), e);
                }
            }
            
            log.info("未处理审批检查完成");
        } catch (Exception e) {
            log.error("检查未处理审批时发生异常", e);
        }
    }
}